package com.lu.pojo.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author luzhenfang
 * @date 2020 05 27
 * @description 通过反射创建对象
 */

public class TestCreateClass {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
        Class<?> aClass = Class.forName("com.lu.pojo.reflection.Cat");
        // 本质 类的无参构造
        Cat o = (Cat) aClass.newInstance();
        System.out.println(o);
        // 通过构造器创建对象
        Constructor<?> constructor = aClass.getDeclaredConstructor(int.class, int.class);
        Cat c1 = (Cat) constructor.newInstance(2, 4);
        System.out.println(c1);
        // 通过反射调用普通方法
        Cat  c2 = (Cat) aClass.newInstance();
        Method getAge = aClass.getDeclaredMethod("setAge", int.class);
        getAge.invoke(c2, 3);
        System.out.println(c2);
        // 设置属性值(如果需要操作私有属性则需要关闭安全检测）
        Field leg = aClass.getDeclaredField("leg");
        // 关闭安全检测
        leg.setAccessible(true);
        leg.set(c2,4);
        System.out.println(c2);



    }
}
